-- 定时器
-- 新血战里的

local skynet = require "skynet"
local filelog = require "filelog"
local timer = require "timer"
local tabletool = require "tabletool"
local timetool = require "timetool"
require "mjexenum"

local filename = "tabletimer.lua"

local TableTimer = {}
local CMD = { }
local service = {}
local tableobj = nil
local tablelogic = nil
local gamelogic = nil

--[Comment]
-- init
--
function TableTimer.init(caller)
	service = caller
	tableobj = service.table_data
	tablelogic = service:get_logicbyname("tablelogic")
	gamelogic = service:get_logicbyname("gamelogic")
end

--[Comment]
-- 处理发来的timer命令消息
--
function TableTimer.timer( msgname, ...)
    local f = CMD[msgname]
    if f == nil then
        return
    end
    return f(...)
end

-----------------------------

--[Comment]
-- 一局游戏开始
--
function CMD.one_game_start(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_ONE_WAIT_GAME_START then
		return
	end

	tableobj.timer_id = -1
   if tableobj.is_roll_dice then   --摇骰子
	    tableobj.state = EMJTableState.TABLE_STATE_MJ_SHAKE_DICE
    else
        tableobj.state = EMJTableState.TABLE_STATE_MJ_DEAL_CARDS
    end
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 一局游戏结束
--
function CMD.onegamerealend(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_ONE_GAME_REAL_END then
		return
	end

	tableobj.timer_id = -1
	tableobj.state = EMJTableState.TABLE_STATE_ONE_GAME_REAL_END
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 等待发送消息
--
function CMD.wait_send_msg(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	tableobj.timer_id = -1
	gamelogic.send_ts_dj_hz_msgs(tableobj)
end

--[Comment]
-- 申请解散,超时自动同意
--
function CMD.applydisband(timerid, request)
	if timerid ~= tableobj.disband_table_timer_id then 
		return
	end

	tableobj.disband_table_timer_id = -1
	if tablelogic.is_gameend(tableobj) or tableobj.playerdisbandlist == nil then
		return
	end

    local is_success = true
    for k,v in pairs(tableobj.playerdisbandlist) do
        if v.is_agree == 2 then
            is_success = false
        end
    end
    
    local noticemsg = {
            table_index = tableobj.index,
            is_success = is_success,
    }
    tablelogic.sendmsg_to_alltableplayer(tableobj, "disbandresultN", noticemsg)

    tableobj.playerdisbandlist = nil
    if is_success then
        tablelogic.disbandtable(tableobj)
    end
end

--[Comment]
-- 摇骰子
--
function CMD.shake_dice(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_SHAKE_DICE then
		return
	end

	tableobj.timer_id = -1

	tableobj.state = EMJTableState.TABLE_STATE_MJ_DEAL_CARDS
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 发牌
--
function CMD.deal_cards(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_DEAL_CARDS then
		return
	end

	tableobj.timer_id = -1

	if tableobj.is_huansanzhang then
		tableobj.state = EMJTableState.TABLE_STATE_MJ_HUAN_SAN_ZHANG
	elseif tableobj.is_dingque then
		tableobj.state = EMJTableState.TABLE_STATE_MJ_DINGQUE
    else
        tableobj.state = EMJTableState.TABLE_STATE_DEAL_BANKER_FIRST_ACTION
	end
   
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 换三张
--
function CMD.huan_san_zhang(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_HUAN_SAN_ZHANG then
		return
	end
    tableobj.timer_id = -1

    for _,seat in pairs(tableobj.seats) do
        if not seat.had_huansanzhang then
            if tableobj.table_type == EMJTableType.TABLE_TYPE_ZIJIAN_FANGKA then    --房卡场不自动换三张
                return
            end
            seat.had_huansanzhang = true
        end
    end

	tableobj.state = EMJTableState.TABLE_STATE_CONTINUE_HUANSANZHANG
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 通知定缺
--
function CMD.do_ding_que(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_DINGQUE then
		return
	end

	tableobj.timer_id = -1
	tableobj.state = EMJTableState.TABLE_STATE_MJ_DINGQUE
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 定缺
--
function CMD.ding_que(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_DINGQUE then
		return
	end
    tableobj.timer_id = -1

    for _,seat in pairs(tableobj.seats) do
        if not seat.que_cardcolor then
            if tableobj.table_type == EMJTableType.TABLE_TYPE_ZIJIAN_FANGKA then    --房卡场不自动定缺
                return
            end
            seat.que_cardcolor = tableobj.que_color_list[seat.index]
        end
    end

	tableobj.state = EMJTableState.TABLE_STATE_CONTINUE_DINGQUE
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 等待庄家操作
--
function CMD.wait_banker_action(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_DINGQUE_RESULT then
		return
	end

	tableobj.timer_id = -1
	tableobj.state = EMJTableState.TABLE_STATE_DEAL_BANKER_FIRST_ACTION
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 选择
--
function CMD.do_select(timerid,request)
    if timerid ~= tableobj.timer_id then
		return
	end
    if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_CLIENT_ACTION then
		return
	end

	tableobj.timer_id = -1
    if tableobj.conf.table_type ~= EMJTableType.TABLE_TYPE_ZIJIAN_FANGKA then   --房卡场，超时一直等待
        gamelogic.handler_select_timeout(tableobj.gameobj)
    end
end

--[Comment]
-- 摸牌
--
function CMD.do_mopai(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_DO_MOPAI then
		return
	end

	tableobj.timer_id = -1

	tableobj.state = EMJTableState.TABLE_STATE_MJ_DO_MOPAI
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 真正摸牌
--
function CMD.do_real_mopai(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_MJ_WAIT_DO_REAL_MOPAI then
		return
	end
	tableobj.timer_id = -1

	tableobj.state = EMJTableState.TABLE_STATE_MJ_DO_REAL_MOPAI
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 处理胡牌
--
function CMD.on_action_type_hupai(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_HUPAI then
		return
	end

	tableobj.timer_id = -1

	tableobj.state = EMJTableState.TABLE_STATE_MJ_HUPAI
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 处理查大叫
--
function CMD.do_cha_da_jiao(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_CHA_DA_JIAO then
		return
	end

	tableobj.timer_id = -1

	tableobj.state = EMJTableState.TABLE_STATE_MJ_CHA_DA_JIAO
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 处理摸牌
--
function CMD.action_type_mopai(timerid, request)
	if timerid ~= tableobj.timer_id then
		return
	end

	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_MOPAI then
		return
	end

	tableobj.timer_id = -1

	tableobj.state = EMJTableState.TABLE_STATE_MJ_MOPAI
	gamelogic.run(tableobj.gameobj)	
end

--[Comment]
-- 准备
--
function CMD.doready(timerid, request)
	local seat = tableobj.seats[request.seat_index]	
	if seat.rid ~= request.rid then
		return
	end
	if timerid ~= seat.ready_timer_id then 
		return
	end
	
    seat.ready_timer_id = -1

	--钻石场，准备超时将玩家站起，并踢出房间
	seat.ready_to_time = nil
    seat.ready_timeout_time = nil
    if tableobj.conf.table_type == EMJTableType.TABLE_TYPE_ZIJIAN_ZUANSHI 
    or tableobj.conf.table_type == EMJTableType.TABLE_TYPE_JIN_BI_CHANG then
        local rid,diamond = seat.rid,seat.playerinfo.diamond
	    tablelogic.passive_standuptable(tableobj, request, seat, EStandupReason.STANDUP_REASON_READYTIMEOUT_STANDUP)	
        tablelogic.passive_leavetable(tableobj,rid,diamond)
    elseif tableobj.conf.table_type == EMJTableType.TABLE_TYPE_LIAN_XI_CHANG then
        if seat.is_robot then
            local roledata = {
                info = {rid = seat.rid},
                money = { fangka = seat.playerinfo.fangka,diamond = seat.playerinfo.diamond,dou = seat.playerinfo.dou},
            }
            local request = { table_index = tableobj.index}
            local ret = skynet.call(tableobj.table_service,"lua","request","gameready",seat.rid,roledata,request)
            if ret.retcode ~= nil then
                filelog.sys_info(ret.retstr)
            else
                timer.settimer(100,"do_robot_tuoguan")
            end
        else
            local rid,diamond = seat.rid,seat.playerinfo.diamond
	        tablelogic.passive_standuptable(tableobj, request, seat, EStandupReason.STANDUP_REASON_READYTIMEOUT_STANDUP)	
            tablelogic.passive_leavetable(tableobj,rid,diamond)
        end
    end
end

--[Comment]
-- 机器人准备
--
function CMD.robot_do_ready(timerid, request)
    if tableobj.table_type ~= EMJTableType.TABLE_TYPE_LIAN_XI_CHANG then
        return
    end

    local seat = tableobj.seats[request.seat_index]	
    local roledata = {
        info = {rid = seat.rid},
        money = { fangka = seat.playerinfo.fangka,diamond = seat.playerinfo.diamond,dou = seat.playerinfo.dou},
    }
    local request = { table_index = tableobj.index}
    local ret = skynet.call(tableobj.table_service,"lua","request","gameready",seat.rid,roledata,request)
    if ret.retcode ~= nil then
        filelog.sys_info(ret.retstr)
    else
        timer.settimer(100,"do_robot_tuoguan")
    end
end

--[Comment]
-- 处理玩家操作
--
function CMD.doaction(timerid, request)
	if tableobj.timer_id ~= timerid then
		return
	end
 	tableobj.timer_id =-1

    --房卡场一直等待
    if tableobj.conf.table_type == EMJTableType.TABLE_TYPE_ZIJIAN_FANGKA then
        --什么也不做
    else   --钻石场，练习场，出当前摸的牌
	    gamelogic.handler_chupai_timeout(tableobj.gameobj)   --超时处理
    end
end

--[Comment]
-- 游戏准备开始
--
function CMD.game_ready_start(timerid, request)
	if tableobj.timer_id ~= timerid then
		return
	end
 	tableobj.timer_id =-1
 	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_ALL_READY then
 		return
 	end

 	for _, seat in pairs(tableobj.seats) do
 		if gamelogic.is_ingame(tableobj.gameobj, seat) then
 			seat.state = EMJSeatState.SEAT_STATE_WAIT_START 			
 		end
 	end 	
 	tableobj.state = EMJTableState.TABLE_STATE_ONE_GAME_START

	gamelogic.run(tableobj.gameobj)
end

--[Comment]
-- 删除桌子
--
function CMD.delete_table(timerid, request)
    if tableobj.delete_table_timer_id == timerid then
        local timeout = 1
        if tableobj.table_type ~= EMJTableType.TABLE_TYPE_ZIJIAN_FANGKA then
            timeout = tableobj.table_persist or 10 --默认10s
        end
        tableobj.delete_table_timer_id = timer.settimer(timeout * 100,"real_delete_table")
    end 
end

--[Comment]
-- 真正删除桌子
--
function CMD.real_delete_table(timerid, request)
    if tableobj.delete_table_timer_id == timerid then
        tableobj.delete_table_timer_id = -1
        --保存游戏记录
        if tableobj.game_records and tableobj.game_records.delete_reason == 0 then
            tableobj.game_records.end_time = tableobj.one_end_time or 0
            tableobj.game_records.final_to_num = tableobj.curr_to_num or 0
            tableobj.game_records.delete_reason = EMJTableDeleteReason.DELETE_REASON_TABLE_NO_PLAYER
        end
        skynet.send(tableobj.table_service,"lua", "delete")
    end 
end

--[Comment]
----用于客户端展示牌局游戏结果界面定时器时间到
--
function CMD.onegameend(timerid, request)
	if tableobj.timer_id ~= timerid then
		return
	end
	
	tableobj.timer_id = -1
	tableobj.state = EMJTableState.TABLE_STATE_ONE_GAME_END
	gamelogic.run(tableobj.gameobj)
end

--[Comment]
-- 延迟处理断线重连
--
function CMD.reenter_table(timerid,request)
    local seat = tableobj.seats[request.seat_index]
    tablelogic.reentertable(tableobj,nil,seat)
end

--[Comment]
-- 托管操作
--
function CMD.tuoguan_doaction(timerid, request)
	local seat = tableobj.seats[request.index]
	if seat.rid ~= request.rid 
		or seat.tuoguan_doaction_timerid ~= timerid then
		return
	end

    filelog.sys_info(seat.rid .. "  do tuo guan")
	seat.tuoguan_doaction_timerid = -1
	gamelogic.dotuoguan(tableobj.gameobj, seat)
end

--[Comment]
-- 用户托管
--
function CMD.do_tuoguan(timerid, request)
    if request == nil or request.index == nil then
        return
    end

	local seat = tableobj.seats[request.index]
    if tableobj.conf.table_type ~= EMJTableType.TABLE_TYPE_ZIJIAN_FANGKA then
        if seat.is_disconnected and not seat.is_tuoguan then
	        seat.is_tuoguan = true  --断线自动托管
            local noticemsg = {
		        rid = seat.rid,
		        seat_index = seat.index,	
                is_tuoguan = seat.is_tuoguan,
	        }
            tablelogic.sendmsg_to_alltableplayer(tableobj,"dotuoguanN", noticemsg)
            local cur_time = timetool.get_time()
            local item = "" .. cur_time .. "_" .. seat.rid .. "_" .. "start_tuoguan"
            tablelogic.save_playback_record(item)
        end
    end
end

--[Comment]
-- 机器人托管
--
function CMD.do_robot_tuoguan(timerid, request)
    if request == nil or request.index == nil then
        return
    end

	local seat = tableobj.seats[request.index]
    if tableobj.conf.table_type == EMJTableType.TABLE_TYPE_LIAN_XI_CHANG then
	    seat.is_tuoguan = true  --自动托管
        seat.is_robot = true
    end
end


--[Comment]
-- 旁观
--
function CMD.do_watch(timerid, request)
    if not request or request.rid == nil then
        return
    end

    if tableobj.waits[request.rid] ~= nil then
        tablelogic.passive_leavetable(tableobj, request.rid, request.diamond)
    end
end

--[Comment]
-- 等待游戏开始
--
function CMD.wait_gamestart(timerid, request)
    if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_GAME_START then
        return
    end

    tableobj.state = EMJTableState.TABLE_STATE_GAME_START
    gamelogic.run(tableobj.gameobj)
end

--[Comment]
-- 等待客户端充值
--
function CMD.wait_charge(timerid, request)
    if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_CHARGE then
        return
    end

    --检测认输玩家
    for _,seat in pairs(tableobj.seats) do
        if not seat.is_hupai and not seat.is_giveup 
        and tableobj.init_diamond_list[seat.rid] <= 0 then
            seat.is_giveup = true
            seat.is_gameend = true
            --通知认输
            local noticemsg = {
                rid = seat.rid,
                seat_index = seat.index,
            }
            tablelogic.sendmsg_to_alltableplayer(tableobj, "giveupN", noticemsg)
        end
    end

    --继续摸牌
    tableobj.state = EMJTableState.TABLE_STATE_WAIT_MJ_DO_MOPAI
	local timer_id = timer.settimer(200, "do_mopai")
	if tableobj.state ~= EMJTableState.TABLE_STATE_WAIT_MJ_DO_MOPAI then
		timer.cleartimer(timer_id)
	else
		tableobj.timer_id = timer_id
	end
    return
end

return TableTimer